﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ElGaleticia;
using ElGaleticia.Cipher;
using ElGaleticia.Cipher.Math;
using System.Security.Cryptography;


namespace ElgaleticiaForms
{
    public partial class Form1 : Form
    {
        ElGamal.EG_Secret_Key secretKey;
        //ElGamal.EG_Public_Key publicKey;
        BigInteger biDigest;

        public Form1()
        {
            InitializeComponent();
            label1.Text = "";
			button2.Enabled = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //gera uma chave privada de tamanho 256bit = 32bytes
            secretKey = ElGamal.GenerateKey(256);

            //gera a chave publica de uma dada chave privada
            ElGamal.EG_Public_Key publicKey = ElGamal.secKey2Pub(secretKey);

            textBox3.Text = Convert.ToBase64String(ElGamal.formatEGPubKey(0, publicKey));

			button2.Enabled = true;
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            byte[] data = Helper.StringToBytes(textBox1.Text);

            //digest = hash(mensagem)
            //byte[] digest = new byte[data.Length];
            //sha1 é uma função hash 
            SHA1 sha = new SHA1CryptoServiceProvider();
            biDigest = new BigInteger(sha.ComputeHash(data));
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                BigInteger[] signature = ElGamal.Sign(biDigest, secretKey);
                textBox4.Text = Convert.ToBase64String(signature[0].getBytes());
                textBox2.Text = Convert.ToBase64String(signature[1].getBytes());
            }
            catch (NullReferenceException)
            {
                DialogResult dialog;
                dialog = MessageBox.Show("É necessário uma mensagem para ser assinada!");
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                BigInteger[] signature = new BigInteger[2];
                signature[0] = new BigInteger(Convert.FromBase64String(textBox4.Text));
                signature[1] = new BigInteger(Convert.FromBase64String(textBox2.Text));
                ElGamal.EG_Public_Key publicKey = ElGamal.parseEGPubKey(Convert.FromBase64String(textBox3.Text));
                bool verify = ElGamal.Verify(signature, biDigest, publicKey);
                label1.Text = verify ? "Válido" : "Inválido";
            }
            catch (FormatException)
            {
                label1.Text = "Inválido";
            }
        }
    }
}
